﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Kiiro.SiteDefinition.MasterPage;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class NewTask : BasePage
    {
        #region Properties
        private List<TeamMember> projectTeamMembers;
        public List<TeamMember> ProjectTeamMembers
        {
            get { return projectTeamMembers; }
            set { projectTeamMembers = value; }
        }

        public Work Work
        {
            get;
            set;
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachmentControl; }
        }

        public TeamMemberCollection TeamMembers
        {
            get { return ( TeamMemberCollection ) teamMemberList; }
        }

        public string UrlReferrer
        {
            get
            {
                string urlReferrer = default ( string );

                if ( ViewState [ "UrlReferrer" ] != null )
                    urlReferrer = ( string ) ViewState [ "UrlReferrer" ];
                else if ( Request.UrlReferrer != null )
                    urlReferrer = Request.UrlReferrer.ToString ( );

                return urlReferrer;
            }
            set { ViewState [ "UrlReferrer" ] = value; }
        }

        public double HoursPerDay
        {
            get { return SetupModel.GetHoursPerDay ( SiteCollectionId, ServerRelativeUrl ); }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );

            CustomFields.ControlMode = SPControlMode.New;
            Buttons.SaveButton.ControlMode = SPControlMode.New;
            Buttons.CancelButton.ControlMode = SPControlMode.New;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            CustomFields.EntityType = typeof ( Work );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( Work ), 0, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.New;

            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            litTitle.Text = "New Task";

            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - New Task";
            }

            if ( PermissionBitsWork [ 0 ] )
            {
                ProjectTeamMembers = TeamModel.GetTeamMembers ( SiteCollectionId, ServerRelativeUrl );

                if ( KiiroMaster.V2Header.Project != null )
                {
                    lblTimeUnit.Text = KiiroMaster.V2Header.Project.TimeMetric.ToString ( );
                }

                if ( !Page.IsPostBack )
                {
                    UrlReferrer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString ( ) : ServerRelativeUrl + Constants.ProjectFileUrls.MyWork;

                    txtPercentage.Text = "0";

                    TeamMembers.TeamMembers = ProjectTeamMembers;
                    TeamMembers.ReadOnly = false;

                    if ( Request.UrlReferrer != null && Request.UrlReferrer.OriginalString != null &&
                        ( Request.UrlReferrer.OriginalString.Contains ( Constants.ProjectFileUrls.MyWork )
                        || Request.UrlReferrer.OriginalString.Contains ( Constants.ProjectFileUrls.WorkAll ) )
                        )
                    {
                        lnkBack.NavigateUrl = UrlReferrer;
                        pnlActionBar.Visible = true;
                    }
                }
            }
            else
            {
                // security error
                Response.Redirect ( Cancel ( ) );
            }
        }
        #endregion

        internal override string Cancel ( )
        {
            string url = String.Format ( "{0}/MyWork.aspx", ServerRelativeUrl );

            if ( !string.IsNullOrEmpty ( UrlReferrer ) )
                url = UrlReferrer;

            return url;
        }

        internal override bool Save ( )
        {
            Work = new Work ( );
            PopulateErrorMessages ( );

            if ( PermissionBitsWork [ 0 ] )
            {
                Work.CreatedBy = CurrentUser;
                Work.CreatedDate = DateTime.Now;
                Work.ServerRelativeUrl = ServerRelativeUrl;
                Work.SiteCollectionId = SiteCollectionId;
                Work.ModifiedBy = CurrentUser;
                Work.ModifiedDate = DateTime.Now;
                Work.Title = txtTitle.Text.Trim ( );
                Work.Description = txtDescription.Text;
                Work.StatusNote = txtStatusNote.Text;
                Work.WorkItemType = WorkType.Task;
                Work.PercentageComplete = string.IsNullOrEmpty ( txtPercentage.Text ) ? default ( float ) : float.Parse ( txtPercentage.Text );

                ValidationMessage message = null;

                double txtNumber = 0.0;
                bool success = double.TryParse ( txtAssignWork.Text, out txtNumber );
                Work.AssignedWork = string.IsNullOrEmpty ( txtAssignWork.Text ) ? default ( float ) : success ? ( float ) txtNumber : -1;
                Work.AssignedWork = FormattingHelpers.ConvertToMinutes ( Work.AssignedWork, KiiroMaster.V2Header.Project.TimeMetric, HoursPerDay );

                DateTime dt;

                if ( DateTime.TryParse ( txtStartDate.Text, out dt ) || string.IsNullOrEmpty ( txtStartDate.Text ) )
                {
                    Work.StartDate = string.IsNullOrEmpty ( txtStartDate.Text ) ? DateTimeHelpers.Empty : DateTime.Parse ( txtStartDate.Text );
                }
                else
                {
                    message = new ValidationMessage ( ValidationSeverity.Validation, "Start date is not in the correct format. (e.g: 05/17/2007)" );
                    Work.StartDateMessage.Add ( message );
                }

                if ( DateTime.TryParse ( txtEndDate.Text, out dt ) || string.IsNullOrEmpty ( txtEndDate.Text ) )
                {
                    Work.EndDate = string.IsNullOrEmpty ( txtEndDate.Text ) ? DateTimeHelpers.Empty : DateTime.Parse ( txtEndDate.Text );
                }
                else
                {
                    message = new ValidationMessage ( ValidationSeverity.Validation, "End date is not in the correct format. (e.g: 05/17/2007)" );
                    Work.EndDateMessage.Add ( message );
                }

                Work.AssignedToList = TeamMembers.GetSelectedIds ( );
                List<string> membersEmailList = TeamMembers.GetSelectedMembersEmails ( );
                if ( membersEmailList.Count > 0 )
                {
                    string membersEmail = default ( string );
                    foreach ( string email in membersEmailList )
                    {
                        membersEmail = membersEmail + email + ";";
                    }
                    if ( !string.IsNullOrEmpty ( membersEmail ) )
                    {
                        Work.MembersEmail = membersEmail;
                    }
                }
                else
                {
                    Work.MembersEmail = default ( string );
                }
                List<string> projectManagersEmailList = TeamMembers.GetSelectedProjectManagersEmails ( );
                if ( projectManagersEmailList.Count > 0 )
                {
                    string projectManagersEmail = default ( string );
                    foreach ( string email in projectManagersEmailList )
                    {
                        projectManagersEmail = projectManagersEmail + email + ";";
                    }
                    if ( !string.IsNullOrEmpty ( projectManagersEmail ) )
                    {
                        Work.ProjectManagersEmail = projectManagersEmail;
                    }
                }
                else
                {
                    Work.ProjectManagersEmail = default ( string );
                }

                Work.AttachmentList = Attachments.GetAttachments ( );
                Work.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                Work.EditType = EditType.Created;
                Work.AttachmentList = Attachments.ValidateFileExtension(Work.AttachmentList);

                Work = WorkModel.Save ( Work, SiteCollectionId, ServerRelativeUrl );

                if ( Work.IsValid ( ) )
                    Response.Redirect ( Cancel ( ) );
                else
                    PopulateErrorMessages ( );
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
            return true;
        }

        private void PopulateErrorMessages ( )
        {
            lblStatusNoteMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.StatusNoteMessage );
            lblStatusNoteMessage.Visible = !string.IsNullOrEmpty ( lblStatusNoteMessage.Text );

            lblStartDateMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.StartDateMessage );
            lblStartDateMessage.Visible = !string.IsNullOrEmpty ( lblStartDateMessage.Text );

            lblEndDateMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.EndDateMessage );
            lblEndDateMessage.Visible = !string.IsNullOrEmpty ( lblEndDateMessage.Text );

            lblDescriptionMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.DescriptionMessage );
            lblDescriptionMessage.Visible = !string.IsNullOrEmpty ( lblDescriptionMessage.Text );

            lblTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.TitleMessage );
            lblTitleMessage.Visible = !string.IsNullOrEmpty ( lblTitleMessage.Text );

            lblAssignWorkMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.AssignedWorkMessage );
            lblAssignWorkMessage.Visible = !string.IsNullOrEmpty ( lblAssignWorkMessage.Text );

            lblDescriptionMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.DescriptionMessage );
            lblDescriptionMessage.Visible = !string.IsNullOrEmpty(lblDescriptionMessage.Text);

            Attachments.ValidationMessage = FormattingHelpers.GetErrorMessageText(Work.AttachmentListMessage);
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Work/NewTask.aspx.cs $
 * 
 * 19    2/08/10 2:28p Camerons
 * 
 * 18    1/11/10 11:51a Camerons
 * 
 * 17    1/06/10 12:39p Camerons
 * 
 * 16    12/14/09 2:10p Shafia
 * attachments file extensions validation for discussions, tasks, and
 * issues
 * 
 * 15    10/26/09 11:47a Adamw
 * Case 332
 * 
 * 14    21/10/09 11:29a Shafia
 * Added validation that Estimated time is a number before parsing it to
 * float. If not a number it will show a validation error.
 * 
 * 13    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 12    19/08/09 12:16p Camerons
 * Fixed get for UrlReferrer property
 * 
 * 11    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/